//
//  ASNetworkEngine.m
//
//  Created by dfangjun on 16-2-14.
//  Copyright (c) dfangjun. All rights reserved.
//

#import "ASNetworkEngine.h"
#import "AFNetworking.h"

@interface ASNetworkEngine()

@property (nonatomic,strong,readwrite) NSURL *requestURL;

@end


@implementation ASNetworkEngine


+ (instancetype)sharedInstance
{
    return [[self alloc] initWithBaseURL:nil];
}

- (instancetype)init
{
    return [self initWithBaseURL:nil];
}

- (instancetype)initWithBaseURL:(NSURL *)url
{
    self = [super init];
    
    if (!self)
    {
        return nil;
    }
    
    self.requestURL = url;
    
    //self.requestSerializer = [AFHTTPRequestSerializer serializer];
    //self.responseSerializer = [AFJSONResponseSerializer serializer];
    
    //self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    
    //self.operationQueue = [[NSOperationQueue alloc] init];
    
    return self;
}

- (void)setHeadParameters:(NSDictionary*)headDic sessionMgr:(AFHTTPSessionManager*)sessionMgr
{
    if (headDic && headDic.count > 0)
    {
        for(NSString* key in headDic.allKeys)
        {
            NSString* value = [headDic objectForKey:key];
            [sessionMgr.requestSerializer setValue:key forHTTPHeaderField:value];
        }
    }
}

//- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer
//{
//    NSParameterAssert(requestSerializer);
//    
//    _requestSerializer = requestSerializer;
//}
//
//- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer
// {
//    NSParameterAssert(responseSerializer);
//    
//    _responseSerializer = responseSerializer;
//}

//- (void)HTTPRequestOperationWithRequest:(NSURLRequest *)request
//                                                    success:(void (^)( id responseObject))success
//                                                    failure:(void (^)( NSError *error))failure
//{
//    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    operation.responseSerializer = self.responseSerializer;
//    operation.shouldUseCredentialStorage = YES;
//    [operation setCompletionBlockWithSuccess:success failure:failure];
//    self.tempOperation = operation;
//    return operation;
//}

#pragma mark - POST

- (void)POST:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    [self POST:URLString headParameters:nil parameters:parameters success:success failure:failure];
}

- (void)POST:(NSString *)URLString
                  headParameters:(id)headParameters
                      parameters:(id)parameters
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    [self POST:URLString headParameters:headParameters bodyParameters:parameters isBodyEncoding:NO success:success failure:failure];
}

- (void)POST:(NSString *)URLString
                  headParameters:(id)headParameters
                      bodyParameters:(id)bodyParameters
                    isBodyEncoding:(BOOL)isBodyEncoding
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    NSURL *url= [NSURL URLWithString:URLString] ;
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    if (headParameters)
    {
        [self setHeadParameters:headParameters sessionMgr:sessionManager];
    }

    [sessionManager POST:[url absoluteString] parameters:bodyParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
    
}

#pragma mark - PUT

- (void)PUT:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    [self PUT:URLString headParameters:nil parameters:parameters success:success failure:failure];
}

- (void)PUT:(NSString *)URLString
                  headParameters:(id)headParameters
                      parameters:(id)parameters
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    [self PUT:URLString headParameters:headParameters bodyParameters:parameters isBodyEncoding:NO success:success failure:failure];
}

- (void)PUT:(NSString *)URLString
                  headParameters:(id)headParameters
                  bodyParameters:(id)bodyParameters
                  isBodyEncoding:(BOOL)isBodyEncoding
                         success:(void (^)( id responseObject))success
                         failure:(void (^)( NSError *error))failure
{
    NSURL *url= [NSURL URLWithString:URLString] ;
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    if (headParameters)
    {
        [self setHeadParameters:headParameters sessionMgr:sessionManager];
    }
    
    [sessionManager PUT:[url absoluteString] parameters:bodyParameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

#pragma mark - GET

- (void)GET:(NSString *)URLString
                     parameters:(id)parameters
                        success:(void (^)( id responseObject))success
                        failure:(void (^)( NSError *error))failure
{
    
    [self GET:URLString headParameters:nil parameters:parameters success:success failure:failure];
}

- (void)GET:(NSString *)URLString
                 headParameters:(NSDictionary*)headParameters
                     parameters:(id)parameters
                        success:(void (^)( id responseObject))success
                        failure:(void (^)( NSError *error))failure
{
    [self GET:URLString headParameters:headParameters parameters:parameters DownloadProgress:nil success:success failure:failure];
}

- (void)GET:(NSString *)URLString
                 headParameters:(NSDictionary*)headParameters
                     parameters:(id)parameters
               DownloadProgress:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))downLoadProgress
                        success:(void (^)( id responseObject))success
                        failure:(void (^)( NSError *error))failure
{
    NSURL *url= [NSURL URLWithString:URLString] ;
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    if (headParameters)
    {
        [self setHeadParameters:headParameters sessionMgr:sessionManager];
    }
    
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [sessionManager GET:[url absoluteString] parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        if (downLoadProgress)
        {
            downLoadProgress(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount, 0);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

- (void)GETImage:(NSString *)URLString
                          parameters:(id)parameters
                             success:(void (^)( id responseObject))success
                             failure:(void (^)( NSError *error))failure
{
    [self GETImage:URLString parameters:parameters DownloadProgress:nil success:success failure:failure];
}

- (void)GETImage:(NSString *)URLString
                          parameters:(id)parameters
                    DownloadProgress:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))downLoadProgress
                             success:(void (^)( id responseObject))success
                             failure:(void (^)( NSError *error))failure
{
    NSURL *url= [NSURL URLWithString:URLString] ;
    if (url == NULL)
    {
        return;
    }
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
    
    //sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [sessionManager GET:[url absoluteString] parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        if (downLoadProgress)
        {
            downLoadProgress(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount, 0);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

#pragma mark - NSObject
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p, requestURL: %@, operationQueue: %@>",
            NSStringFromClass([self class]),
            self,
            self.requestURL,
            self.operationQueue];
}


- (void)cancelAllHTTPOperationsWithMethod
{
    [self.operationQueue cancelAllOperations];
}

@end







